<?php


namespace Yoc\canvas;


use BeReborn\Canvas\AbstractCanvas;
use BeReborn\Canvas\Canvas;
use Exception;

/**
 * Class Text
 * @package Yoc\canvas
 */
class Text extends AbstractCanvas implements Canvas
{

	private $_text = '';

	private $_fontType = '';

	private $_fontSize = '';

	private $_color = '';

	private $_backgroundColor = [];

	/**
	 * @return string
	 */
	public function getText()
	{
		return $this->_text;
	}

	/**
	 * @param string $text
	 */
	public function setText(string $text): void
	{
		$this->_text = $text;
	}

	/**
	 * @return string
	 */
	public function getFontType()
	{
		return $this->_fontType;
	}

	/**
	 * @param string $fontType
	 */
	public function setFontType(string $fontType): void
	{
		$this->_fontType = $fontType;
	}

	/**
	 * @return string
	 */
	public function getFontSize()
	{
		return $this->_fontSize;
	}

	/**
	 * @param string $fontSize
	 */
	public function setFontSize(string $fontSize): void
	{
		$this->_fontSize = $fontSize;
	}

	/**
	 * @return string
	 */
	public function getColor()
	{
		return $this->_color;
	}

	/**
	 * @param string $color
	 */
	public function setColor(string $color): void
	{
		$this->_color = $color;
	}

	/**
	 * @return array
	 */
	public function getBackgroundColor(): array
	{
		return $this->_backgroundColor;
	}

	/**
	 * @param array $backgroundColor
	 * @throws Exception
	 */
	public function setBackgroundColor(array $backgroundColor): void
	{
		if (!isset($backgroundColor['r'], $backgroundColor['g'], $backgroundColor['b'])) {
			throw new Exception('参数残缺不全!');
		}
		$this->_backgroundColor = $backgroundColor;
	}


	/**
	 * @throws Exception
	 */
	public function Draw()
	{
		$this->setWidth($this->getFontWidth());
		$this->setHeight($this->getFontWidth());

		$source = $this->instance();
		if (!empty($this->getBackgroundColor())) {
			$this->DrawBackgroundColor(...$this->getBackgroundColor());
		}
		imagefttext($source, $this->getFontSize(), 0, $this->getX(), $this->getY(), $this->getColor(), $this->getFontType(), $this->_text);
	}


	/**
	 * @return mixed
	 * 字体宽度
	 */
	public function getFontWidth()
	{
		$lists = imagettfbbox($this->getFontSize(), 0, $this->getFontType(), $this->getText());
		return $lists[0] + $lists[2];
	}


	/**
	 * @return mixed
	 * 字体宽度
	 */
	public function getFontHeight()
	{
		$lists = imagettfbbox($this->getFontSize(), 0, $this->getFontType(), $this->getText());
		return $lists[0] + $lists[2];
	}

}
